package org.vector.boot3x.v34.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api")
public class RestApi {
    //不再使用组件直接注入
    private final RestTemplate restTemplate;

    @Autowired
    public RestApi(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping("/restTest")
    public String   testAdd(String name){
        return  System.currentTimeMillis() + " add success "+name;
    }

    @PutMapping("/restTest")
    public String   testUpdate(){
        return  System.currentTimeMillis() + " update success";
    }

    @GetMapping("/restTest")
    public String   testGet(){
        return  System.currentTimeMillis() + " get success";
    }

    @DeleteMapping("/restTest")
    public String   testDel(){
        return  System.currentTimeMillis() + " del success";
    }

    @GetMapping("/test")
    public String test(){
        String BASE_URI = "http://127.0.0.1:8080/api/restTest";

        RestClient restClient = RestClient.create();

        ResponseEntity<String> postResponse = restClient.post().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试post接口  ===> "+ postResponse.getBody());

        ResponseEntity<String> putResponse = restClient.put().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试put接口   ===> "+ putResponse.getBody());

        ResponseEntity<String>   getResponse = restClient.post().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试get接口   ===> "+getResponse.getBody());

        ResponseEntity<String> delResponse = restClient.delete().uri(BASE_URI).retrieve().toEntity(String.class);
        System.out.println("测试del接口   ===> "+ delResponse.getBody());
        return "del success";
    }

    @GetMapping("/restTemplate")
    public String restTemplate(){
        String BASE_URI = "http://127.0.0.1:8080/api/restTest";

        ResponseEntity<String> postResponse = restTemplate.getForEntity(BASE_URI, String.class);
        System.out.println("测试get接口  ===> "+ postResponse.getBody());

        restTemplate.put(BASE_URI, null,  "");
        System.out.println("测试put接口   ===> ");

        ResponseEntity<String> getResponse = restTemplate.postForEntity(BASE_URI, null,  String.class);
        System.out.println("测试post接口   ===> "+getResponse.getBody());

        restTemplate.delete(BASE_URI);
        System.out.println("测试delete接口   ===> ");
        return "del success";
    }
}
